<template>
  <div class="operation-container">
    <!-- 工序主信息卡片 -->
    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="title-wrapper">
            <h2 class="operation-title">
              <i class="el-icon-s-operation title-icon"></i>
              {{ operation.operationName }}
            </h2>
            <el-tag
                v-if="operation.isQaPoint"
                type="danger"
                effect="dark"
                class="qa-tag"
            >
              <i class="el-icon-finished"></i> 质检点
            </el-tag>
          </div>
        </div>
      </template>

      <div class="operation-info">
        <div class="info-item">
          <el-icon class="info-icon"><Document /></el-icon>
          <div>
            <p class="info-label">工序描述</p>
            <p class="info-value">{{ operation.description || '暂无描述' }}</p>
          </div>
        </div>

        <el-divider class="info-divider" />

        <div class="info-row">
          <div class="info-col">
            <el-icon class="info-icon"><Clock /></el-icon>
            <div>
              <p class="info-label">标准周期时间</p>
              <p class="info-value">{{ operation.standardCycleTime }} {{ operation.unitOfTime }}</p>
            </div>
          </div>

          <div class="info-col">
            <el-icon class="info-icon"><Calendar /></el-icon>
            <div>
              <p class="info-label">创建时间</p>
              <p class="info-value">{{ formatDate(operation.createdAt) }}</p>
            </div>
          </div>

          <div class="info-col">
            <el-icon class="info-icon"><Refresh /></el-icon>
            <div>
              <p class="info-label">更新时间</p>
              <p class="info-value">{{ formatDate(operation.updatedAt) }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <el-table v-loading="loading" :data="componentsWithMaterialName.value" @selection-change="handleProductChange">

        <!--      <el-table-column label="明细ID" align="center" prop="componentId" />-->
<!--        <el-table-column label="BOM ID" align="center" prop="bomId" />-->
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="数量" align="center" prop="quantity" />
        <el-table-column label="计量单位" align="center" prop="unitOfMeasure" />
        <el-table-column label="备注" align="center" prop="notes" />

      </el-table>
    </el-card>

    <!-- 参数列表标题 -->
    <div class="section-header">
      <div class="section-line"></div>
      <h3 class="section-title">
        <i class="el-icon-s-data"></i>
        工序参数要求
      </h3>
      <div class="section-line"></div>
    </div>

    <!-- 参数卡片列表 -->
    <div class="param-grid">
      <el-card
          v-for="param in operation.operationParameters"
          :key="param.paramId"
          class="param-card"
          :class="{ 'single-card': operation.operationParameters.length === 1 }"
      >
        <template #header>
          <div class="param-header">
            <h3 class="param-name">
              <i class="el-icon-odometer"></i>
              {{ param.paramName }}
            </h3>
            <el-tag
                type="info"
                effect="light"
                class="unit-tag"
            >
              {{ param.unitOfMeasure || '无单位' }}
            </el-tag>
          </div>
        </template>

        <div class="param-content">
          <el-row :gutter="20" class="value-row">
            <el-col :span="8">
              <div class="param-value standard">
                <p class="label">标准值</p>
                <p class="value">{{ param.standardValue }}</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="param-value min">
                <p class="label">最小值</p>
                <p class="value">{{ param.minValue }}</p>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="param-value max">
                <p class="label">最大值</p>
                <p class="value">{{ param.maxValue }}</p>
              </div>
            </el-col>
          </el-row>

          <div class="param-description" v-if="param.description">
            <el-divider class="desc-divider" />
            <div class="desc-content">
              <el-icon class="desc-icon"><InfoFilled /></el-icon>
              <p>{{ param.description }}</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="action-footer"style="display: flex; justify-content: center; gap: 10px;margin-top: 20px">
      <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddProduct"
      >
        {{
          RoleOperationId == '1' ? '录入产品' :
              [2,3,4,5].includes(Number(RoleOperationId)) ? '操作产品' :
                  '产品入库'
        }}
      </el-button>
      <add-some :operation-options="operationOptions" :get-product-name="getProductName" :RoleOperationId="userStore.operationId" :add-count="addGoodSomeProducts"></add-some>
      <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddBadProduct"
          v-if="RoleOperationId!='1'"
      >
        残次品上传
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleResult"
        v-if="RoleOperationId!=[6,1]">
        上报工序完成情况
      </el-button>
      <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAddException">
     上报异常
      </el-button>
      <el-button
      type="primary"
      icon="el-icon-plus"
      @click="handleAddProductsByCount"
      v-if="RoleOperationId!=1">
        批量操作产品
      </el-button>

    </div>
    <!--批量处理产品的对话框-->
    <el-dialog v-model="productsWithCountForm"   width="600px"
               append-to-body
               :close-on-click-modal="false">
      <el-form :model="productWithCount" label-width="120">
        <el-form-item label="产品所处工序">:{{RoleOperationId}}</el-form-item>
        <el-form-item label="本次处理产品数" prop="count">
          <el-input v-model="productWithCount.count" placeholder="输入处理产品数量"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitCount">确定</el-button>
      </template>
    </el-dialog>
    <!--添加生产异常的对话框-->
    <el-dialog  v-model="open" width="500px" append-to-body>
      <el-form ref="exceptionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单ID" prop="workOrderId">
          <el-select
              v-model="form.workOrderId"
              placeholder="请选择工单"
              filterable
              clearable
              :loading="loadingWorkOrders"
          >
            <el-option
                v-for="item in workOrderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工序执行记录ID" prop="operationRecordId">
          <el-select
              v-model="form.operationRecordId"
              placeholder="请选择记录ID"
              clearable
              filterable
          >
            <el-option
                v-for="item in recordOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备ID" prop="equipmentId"   >
          <!--          <el-input v-model="form.equipmentId" placeholder="请输入设备ID" />-->
          <el-select
              v-model="form.equipmentId"
              placeholder="请选择设备ID"
              clearable
              filterable
          >
            <el-option
                v-for="item in equipmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常类型" prop="anomalyType">
          <el-select v-model="form.anomalyType" placeholder="请选择异常类型">
            <el-option label="生产异常" value="生产异常" />
            <el-option label="设备异常" value="设备异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常详细描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-input v-model="form.severity" placeholder="请输入严重程度" />
        </el-form-item>

        <!--        <el-form-item label="上报人ID" prop="reportedBy">-->
        <!--          <el-input v-model="form.reportedBy" placeholder="请输入上报人ID" />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="任务状态" prop="status">-->
        <!--            <el-select v-model="form.status" placeholder="请选择任务状态">-->
        <!--                <el-option label="未完成" value="未完成"/>-->
        <!--                <el-option label="已完成" value="已完成"/>-->
        <!--            </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="上报时间" prop="reportTime">
          <el-date-picker clearable
                          v-model="form.reportTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择上报时间">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="处理人ID" prop="resolvedBy">-->
        <!--          <el-input v-model="form.resolvedBy" placeholder="请输入处理人ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="解决时间" prop="resolvedTime">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.resolvedTime"-->
        <!--            type="date"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--            placeholder="请选择解决时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="创建时间" prop="createdAt">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.createdAt"-->
        <!--            type="date"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--            placeholder="请选择创建时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后更新时间" prop="updatedAt">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.updatedAt"-->
        <!--            type="date"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--            placeholder="请选择最后更新时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--残次品录入-->
    <el-dialog
        title="残次品上报"
        v-model="badProductForm"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form :model="BadGoodData" :rules="badGoodRules" ref="badGoodFormRef">
        <el-form-item label="产品编号" prop="productId">
          <el-input
              v-model="BadGoodData.productId"
              placeholder="输入产品编号"
              clearable
          />
        </el-form-item>

        <el-form-item label="产品所处工序">
          {{ BadGoodData.operationId }}
        </el-form-item>

        <el-form-item label="问题描述" prop="problemDes">
          <el-input
              v-model="BadGoodData.problemDes"
              type="textarea"
              placeholder="请输入问题描述"
          />
        </el-form-item>

        <el-form-item label="上报人">
          {{ BadGoodData.supplyer }}
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="badProductForm = false">取消</el-button>
        <el-button type="primary" @click="submitBadGoods">确定</el-button>
      </template>
    </el-dialog>
    <!-- 产品录入对话框 -->
    <el-dialog
        v-if="RoleOperationId === 1"
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form
          ref="productFormRef"
          :model="productForm"
          :rules="productRules"
          label-width="120px"
          label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-select
                  v-model="productForm.productName"
                  placeholder="请选择产品名称"
                  filterable
                  clearable
                  style="width: 100%"
                  @change="handleProductChange"
              >
                <el-option
                    v-for="op in productNames"
                    :key="op.productId"
                    :label="op.productName"
                    :value="op.productName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unitOfMeasure">
              <el-input
                  v-model="productForm.unitOfMeasure"
                  placeholder="如：件、kg、m"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联工序" prop="operationId">
          <el-select
              v-model="productForm.operationId"
              placeholder="请选择关联工序"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="op in operationOptions"
                :key="op.value"
                :label="op.label"
                :value="op.value"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdAt">
              <el-date-picker
                  v-model="productForm.createdAt"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择创建时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updatedAt">
              <el-date-picker
                  v-model="productForm.updatedAt"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择更新时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelProductForm">取 消</el-button>
          <el-button
              type="primary"
              @click="submitProductForm"
              :loading="submitLoading"
          >
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!--操作产品对话框-->
    <el-dialog
        v-else-if="[2,3,4,5].includes(RoleOperationId)"
        title="操作产品"
        v-model="dialogVisible"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form  :model="operateProductForm">
        <el-form-item label="产品编号" prop="productId">
          {{operateProductForm.productId}}
        </el-form-item>
        <!-- 不同的表单内容 -->
        <el-form-item label="产品名称" prop="productName">
          {{operateProductForm.productName}}
        </el-form-item>
         <el-form-item label="关联工序" prop="operationId">
          <el-select
              v-model="operateProductForm.operationId"
              placeholder="请选择关联工序"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="op in operationOptions"
                :key="op.value"
                :label="op.label"
                :value="op.value"
            />
          </el-select>
        </el-form-item>
        <el-col :span="12">
          <el-form-item label="更新时间" prop="updatedAt">
            <el-date-picker
                v-model="operateProductForm.updatedAt"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择更新时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <!-- 其他操作产品特有的字段 -->
      </el-form>
      <template #footer>
        <el-button @click="operateProductForm = false">取消</el-button>
        <el-button type="primary" @click="submitOperateForm">确定</el-button>
      </template>
    </el-dialog>
    <!--上传产品对话框-->
    <el-dialog
        v-else-if="RoleOperationId === 6"
        title="产品入库"
        v-model="dialogVisible"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form  :model="operateProductForm">
        <el-form-item label="产品编号" prop="productId">
          {{operateProductForm.productId}}
        </el-form-item>
        <!-- 不同的表单内容 -->
        <el-form-item label="产品名称" prop="productName">
          {{operateProductForm.productName}}
        </el-form-item>


        <el-col :span="12">
          <el-form-item label="更新时间" prop="updatedAt">
            <el-date-picker
                v-model="operateProductForm.updatedAt"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择更新时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <!-- 其他操作产品特有的字段 -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitToInventory">确定</el-button>
      </template>
    </el-dialog>
    <!--报告工序对话框-->
    <el-dialog
        title="上报工序"
        v-model="resultOp"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form  :model="recordForm" >
        <el-form-item label="工序编号" >
          {{RoleOperationId}}
        </el-form-item>
        <el-form-item label="当前所在工序" >
          {{ operation.operationName }}
        </el-form-item>
        <el-form-item label="操作员" prop="operatorId">
          {{userStore.name}}
        </el-form-item>
        <el-form-item label="良品数量" prop="goodQuantity">
          {{countGoodOperationNum}}
        </el-form-item>
        <el-form-item label="报废数量" prop="scrapQuantity">
          {{badGoodOperationNum}}
        </el-form-item>
        <el-form-item label="设备id" prop="equipmentId">
          <el-input v-model="recordForm.equipmentId" placeholder="请输入设备id" />
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="recordForm.startTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="recordForm.endTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="recordForm.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="recordForm.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitToRecord">确定</el-button>
      </template>
    </el-dialog>
    <!-- 无参数时的提示 -->
    <el-empty
        v-if="operation.operationParameters && operation.operationParameters.length === 0"
        description="暂无工序参数"
        class="empty-tip"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import {getOperationWithParams, listOperations} from '@/api/base-data-service/operations.js'
import {dayjs, ElMessage} from "element-plus"
import {
  Document, Clock, Calendar, Refresh,
  InfoFilled, Odometer
} from '@element-plus/icons-vue'
import {
  addProductionProducts,
  getProductionProductsByRouteId, productionWithCount,
  updateProductionProducts
} from "@/api/production-service/productionProducts.js";
import useUserStore from "@/store/modules/user.js";
import {listProducts} from "@/api/base-data-service/products.js";
import {addGoods} from "@/api/quality-service/goods.js";
import {addInventory} from "@/api/material-service/inventory.js";
import Cookies from "js-cookie";
import {addRecords, listRecords} from "@/api/production-service/records.js";
import {listOrders} from "@/api/workorder-service/orders.js";
import {addException, updateException} from "@/api/production-service/exception.js";
import AddSome from "@/views/production-service/components/addSome.vue";
import {getBomByProductId} from "@/api/base-data-service/boms.js";
import {getMaterials, listComponents} from "@/api/base-data-service/components.js";
import {listMaterials} from "@/api/material-service/materials.js";
const userStore = useUserStore()
const RoleOperationId=userStore.operationId;//修改Role中的角色Id
const operationId =ref(RoleOperationId)  //工序Id
const productNames=ref([])
const dialogVisible = ref(false)
const badProductForm = ref(false)
const submitLoading = ref(false)
const productFormRef = ref(null)
const currentOperationId = ref(null)
const BadGoodData = reactive({
    productId:"" ,
    operationId: operationId.value-1,
    problemDes:"",
    supplyer: userStore.name
  })
const operationOptions = computed(() => [
  {
    value: operationId.value,
    label: `当前工序 (ID: ${operationId.value})`
  },
  {
    value: operationId.value + 1,
    label: `下一工序 (ID: ${operationId.value + 1})`
  }
])
const productWithCount=ref({
  operationId: RoleOperationId,
  count:null,
  updateAt: new Date()

})
const productTypeId = computed(() => operateProductForm.value.productTypeId)
const productsWithCountForm=ref(false)
const { proxy } = getCurrentInstance()
const getCountKey = (prefix) => `${prefix}_${userStore.id}`
const countGoodOperationNum = ref(0)//用于记录好的产品数量
const badGoodOperationNum = ref(0)//用于记录坏的产品数量
const operateProductForm=ref({ productName: '',
  productDescription: '',
  operationId: RoleOperationId, // 默认关联当前工序
  unitOfMeasure: '',
  createdAt: null,  // 初始化为null，由日期选择器控制
  updatedAt: null,
  productTypeId:''})
const resultOp=ref(false)
const recordForm=ref({
      operationId: null,
      equipmentId: null,
      operatorId: null,
      startTime: null,
      endTime: null,
      goodQuantity: null,
      scrapQuantity: null,
      status: null,
      notes: null,
      createdAt: null,
      updatedAt: null,
  productTypeId:''
})
const open = ref(false)//

const badGoodRules = reactive({
  problemDes: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, message: '问题描述至少10个字符', trigger: 'blur' }
  ]
})

const badGoodFormRef = ref(null) // 添加表单引用
const ExceptionData = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workOrderId: null,
    operationRecordId: null,
    equipmentId: null,
    anomalyType: null,
    description: null,
    severity: null,
    reportedBy: null,
    reportTime: null,
    status: "未完成",
    resolution: null,
    resolvedBy: null,
    resolvedTime: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    anomalyType: [
      { required: true, message: "异常类型不能为空", trigger: "change" }
    ],
    description: [
      { required: true, message: "异常详细描述不能为空", trigger: "blur" }
    ],
    reportTime: [
      { required: true, message: "上报时间不能为空", trigger: "blur" }
    ],
    // createdAt: [
    //   { required: true, message: "创建时间不能为空", trigger: "blur" }
    // ],
    // updatedAt: [
    //   { required: true, message: "最后更新时间不能为空", trigger: "blur" }
    // ]
  }
})
const { queryParams, form, rules,title, queryParamsMaterial } = toRefs(ExceptionData)

function getProductName(){
 return  listProducts().then(response => {
    console.log(response)
    productNames.value = response.rows
    return response.rows
  })
}
getProductName()
const route = useRoute()
const operation = ref({
  operationName: '',
  isQaPoint: false,
  standardCycleTime: '',
  unitOfTime: '',
  createdAt: '',
  updatedAt: '',
  operationParameters: []
})
const productForm = reactive({
  productName: '',
  productDescription: '',
  operationId: RoleOperationId, // 默认关联当前工序
  unitOfMeasure: '',
  createdAt: null,  // 初始化为null，由日期选择器控制
  updatedAt: null,   // 初始化为null，提交时自动生成
  productTypeId:''
})
// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  return new Date(dateString).toLocaleString()
}
const productRules = reactive({

  operationId: [
    { required: true, message: '请选择关联工序', trigger: 'change' }
  ],
  unitOfMeasure: [
    { required: true, message: '请输入计量单位', trigger: 'blur' }
  ]
})


//如果工序id不为1 则获取一个产品的数据
const getProductByOperationId = async () => {
  try {
    const response = await getProductionProductsByRouteId(userStore.operationId);

    // 明确处理 null/undefined 情况
    if (!response?.data) {
      ElMessage.warning('当前工序暂无产品数据');
      operateProductForm.value = {
        productName: '',
        productId: '',
        productTypeId: '', // 关键：初始化 productTypeId 为空字符串
        createdAt: '',
        updatedAt: '',
      };
      return;
    }

    // 安全赋值
    operateProductForm.value = {
      ...response.data,
      productTypeId: response.data.productTypeId || '', // 确保 productTypeId 不为 undefined
    };

    // console.log("当前产品ID:", operateProductForm.value.productTypeId);

  } catch (error) {
    console.error('获取工序数据失败:', error);
    ElMessage.error(`获取工序数据失败: ${error.message}`);
  }
};

const data = reactive({
  form: {},
  queryParamsMaterial: {
    pageNum: 1,
    pageSize: 10,
    bomId: null,
    componentMaterialId: null,
    quantity: null,
    unitOfMeasure: null,
    notes: null,
    createdAt: null,
    updatedAt: null,
    operationId: null
  },
})
const componentsResponse = ref([]);
const materialsList = ref([])
const materialNames = ref([])
const componentsWithMaterialName = ref([]);

const getNeedMaterials = async () => {
  try {
    // 1. 确保数据已加载
    await getProductByOperationId();

    // 2. 获取productTypeId
    const productId = operateProductForm.value?.productTypeId;

    if (!productId) {
      console.warn("产品类型ID为空，请检查数据！");
    } else {
      console.log("当前产品类型ID:", productId);
    }

    // 3. 获取bomID（无论productTypeId是否存在都执行）
    const response = await getBomByProductId(productId); // 使用默认值防止报错
    const bomId = response.bomId
    console.log("BomID:", bomId); // 安全访问

    // 4. 打印当前工序
    console.log("当前工序:", RoleOperationId);

    data.queryParamsMaterial.bomId = bomId;

    data.queryParamsMaterial.operationId = RoleOperationId;
    console.log(data.queryParamsMaterial)
    // 5. 根据bomID和operationId获取需求物料
    listComponents(data.queryParamsMaterial).then(response => {
      componentsResponse.value = response.rows
      total.value = response.total
      loading.value = false
    })
    console.log("111",componentsResponse)
    listMaterials(null).then(response => {
      materialsList.value = response.rows
      materialNames.value = materialsList.value.map(item => ({
        value: item.materialId,
        label: item.materialName
      }))

      total.value = response.total
      loading.value = false
    })
    console.log(materialNames)
    const materialMap = computed(() => {
      return new Map(materialNames.value.map(m => [m.value, m.label])) // 显式返回
    })
    console.log(materialMap)
    componentsWithMaterialName.value = computed(() => {
      return componentsResponse.value.map(c => ({ // 显式返回 + 正确对象语法
        ...c,
        materialName: materialMap.value.get(c.componentMaterialId) || '未知物料'
      }))
    })
    console.log("666",componentsWithMaterialName);
    // const materials = await listMaterials();
    // materialNames.value = materialsList.value.map(item => ({
    //   value: item.materialId,
    //   label: item.materialName
    // }))
    // console.log(materials.rows)
    // if (componentsResponse.length === 0 || !materials?.rows) {
    //   console.error("数据未加载或为空");
    //   return;
    // }
    // const materialMap = computed(() => {
    //   return new Map(materialNames.value.map(m => [m.value, m.label])) // 显式返回
    // })
    //
    // const componentsWithMaterialName = computed(() => {
    //   return componentsResponse.value.map(c => ({ // 显式返回 + 正确对象语法
    //     ...componentsResponse,
    //     materialName: materialMap.value.get(c.componentMaterialId) || '未知物料'
    //   }))
    // })
    //
    // console.log("666",componentsWithMaterialName);

  } catch (error) {
    console.error("执行流程出错:", error);
    // 可以在这里添加统一的错误处理（如弹窗提示）
    ElMessage.error(`操作失败: ${error.message}`);
  }
};

const handleProductChange = (selectedProductName) => {
  if (selectedProductName) {
    const selectedProduct = productNames.value.find(
        p => p.productName === selectedProductName
    );
    if (selectedProduct) {
      productForm.productTypeId = selectedProduct.productId; // 使用实际的 productId
      productForm.unitOfMeasure = selectedProduct.unitOfMeasure || ''; // 同时可以更新其他字段
    }
  } else {
    productForm.productTypeId = '';
    productForm.unitOfMeasure = '';
  }
};
const submitBadGoods = () => {
  badGoodFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保数据完整
        const submitData = {
          ...BadGoodData,
          operationId: operationId.value - 1,
          supplyer: userStore.name,
          reportTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }

        const response = await addGoods(submitData)
        if (response.code === 200) {
          ElMessage.success("残次品上报成功")
          badProductForm.value = false
          addBad() // 更新坏品计数
          resetBadGoodForm() // 重置表单
        } else {
          ElMessage.error(response.msg || "上报失败")
        }
      } catch (error) {
        ElMessage.error(`上报出错: ${error.message}`)
      }
    }
  })
}
// 重置表单方法
const resetBadGoodForm = () => {
  BadGoodData.productId = ''
  BadGoodData.problemDes = ''
}
// 获取工序数据
const fetchOperation = async () => {
  try {
    const response = await getOperationWithParams(RoleOperationId)

    console.log("API响应:", response)

    operation.value = {
      ...operation.value,
      ...response.data,
      operationParameters: response.data.operationParameters || []
    }
  } catch (error) {
    console.error('获取工序数据失败:', error)
    ElMessage.error(`获取工序数据失败: ${error.message}`)
  }
}

const handleAddProductsByCount= ()=>{
  productsWithCountForm.value=true


}
const handleAddProduct = () => {
  currentOperationId.value = operation.value.operationId
  productForm.operationId = operation.value.operationId
  dialogVisible.value = true
}
const handleAddBadProduct = () => {
  // 重置表单数据
  resetBadGoodForm()

  // 设置固定值
  BadGoodData.operationId = operationId.value - 1
  BadGoodData.supplyer = userStore.name

  badProductForm.value = true
}
const handleResult =()=>{
  recordForm.value.operatorId=userStore.id
  recordForm.value.goodQuantity=countGoodOperationNum.value
  recordForm.value.scrapQuantity=badGoodOperationNum.value
  recordForm.value.operationId=RoleOperationId
  recordForm.value.productTypeId= Number(operateProductForm.value.productTypeId)
  resultOp.value=true
}
// 提交产品表单
const submitProductForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      // 确保 productTypeId 有值
      if (!productForm.productTypeId) {
        ElMessage.warning('请选择有效的产品');
        return;
      }
      submitLoading.value = true;
      try {
        const formData = {
          ...productForm,

          createdAt: productForm.createdAt
              ? dayjs(productForm.createdAt).format('YYYY-MM-DD HH:mm:ss')
              : dayjs().format('YYYY-MM-DD HH:mm:ss'),
          updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };

        console.log('完整提交数据:', formData); // 调试用
        await addProductionProducts(formData);
        addGood()
        ElMessage.success('产品录入成功');
        dialogVisible.value = false;
        resetProductForm();
      } catch (error) {
        ElMessage.error(`产品录入失败: ${error.message}`);
      } finally {
        submitLoading.value = false;
      }
    }
  });
}
//提交工序产品表单
const submitToInventory = async () =>{
  console.log(operateProductForm.value)
  const mesFinishedGoods = {
    productId: operateProductForm.value.productTypeId,  // 将 productTypeId 映射到 productId
    productFinishedId: operateProductForm.value.productId,  // 将 productId 映射到 product_finished_id
    // 可以继续添加其他需要映射的字段...
  };
  try{
    console.log(mesFinishedGoods)
  await addInventory(mesFinishedGoods)
    ElMessage.success("产品入库成功")
    location.reload()
}catch (error) {
  ElMessage.error(`产品添入库存: ${error.message}`);
}
}
const submitOperateForm = async () => {
  try {
    const formData = {
      ...operateProductForm.value, // 解构原始值
      updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    };

    console.log('提交数据:', formData);
    await updateProductionProducts(formData); // ✅ 确保传入普通对象
    ElMessage.success('操作产品成功');
    addGood()
    console.log("录入的好的产品数量"+countGoodOperationNum.value)
    dialogVisible.value = false;
    getProductByOperationId();
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`);
  }
};
const submitToRecord = async () => {
  try {
    console.log(recordForm.value)
    const response = await addRecords(recordForm.value)

    if (response.code === 200) {
      ElMessage.success('上报成功')
      // 成功后的操作，比如关闭对话框、重置表单等
      resultOp.value = false
      // 可选：重置计数
      countGoodOperationNum.value = 0
      badGoodOperationNum.value = 0
      saveCounts()
    } else {
      ElMessage.error(`上报失败: ${response.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('上报出错:', error)
    ElMessage.error(`上报出错: ${error.message || '网络错误'}`)
  }
}

// 重置表单
const resetProductForm = () => {
  Object.assign(productForm, {
    productName: '',
    productDescription: '',
    operationId: operationId.value, // 保留工序关联
    unitOfMeasure: '',
    createdAt: null,  // 保持为null
    updatedAt: null
  })
}

// 取消表单
const cancelProductForm = () => {
  dialogVisible.value = false
  resetProductForm()
}
//上报异常信息加载
const recordOptions = ref([]);
const equipmentOptions= ref([])
// 查询新建记录中——工序执行记录ID的下拉框
const loadOptions = async () => {
  try {
    const res = await listRecords({
      pageSize: 1000 // 获取足够多的记录
    })

    // 转换数据：假设接口返回的字段是 recordId
    recordOptions.value = res.rows.map(item => ({
      value: item.recordId,  // 实际值对应 recordId
      label: `记录ID: ${item.recordId}` // 下拉显示文本
    }))
    console.log(recordOptions.value)

    // 如果需要显示更多信息（如工单号）：
    // label: `ID: ${item.recordId} (工单: ${item.workOrderId})`
    equipmentOptions.value = res.rows.map(item => ({
      value: item.equipmentId,  // 实际值对应 recordId
      label: `设备ID: ${item.equipmentId}` // 下拉显示文本
    }))
  } catch (error) {
    console.error('加载记录ID列表失败:', error)
  }
}
// 组件挂载时加载选项

//查询工单id
const workOrderOptions = ref([]) // 存储下拉框选项
const loadingWorkOrders = ref(false) // 加载状态
// 获取工单列表数据
const fetchWorkOrders = async () => {
  loadingWorkOrders.value = true
  try {
    const res = await listOrders({
      pageSize: 1000 // 获取足够多的记录
    })

    // 转换数据格式，确保包含 id 和 productName 字段
    workOrderOptions.value = res.rows.map(item => ({
      value: item.id, // 实际存储的值是工单ID
      label: `${item.id} - ${item.productName}` // 下拉框显示的内容
    }))
  } catch (error) {
    console.error('获取工单列表失败:', error)
  } finally {
    loadingWorkOrders.value = false
  }
}

//存储数量的函数
// 保存/加载计数
const saveCounts = () => {
  Cookies.set(getCountKey('goodCount'), countGoodOperationNum.value, { expires: 1 })
  Cookies.set(getCountKey('badCount'), badGoodOperationNum.value, { expires: 1 })
}

const loadCounts = () => {
  countGoodOperationNum.value = Number(Cookies.get(getCountKey('goodCount'))) || 0;
  badGoodOperationNum.value = Number(Cookies.get(getCountKey('badCount'))) || 0;
};
const addGood = () =>{
  countGoodOperationNum.value++
  saveCounts()
}
const addGoodSomeProducts = (num) => {
  console.log(typeof countGoodOperationNum.value, typeof num);
  countGoodOperationNum.value += Number(num); // ✅ 确保 num 是数字
  saveCounts();
};
const addBad = () =>{
  badGoodOperationNum.value++
  saveCounts()
}
// 操作计数
//处理生产异常
function handleAddException() {
  open.value = true
}
function submitForm() {
  proxy.$refs["exceptionRef"].validate(valid => {
    if (valid) {
      form.value.reportedBy=userStore.name
      if (form.value.anomalyId != null) {
        updateException(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addException(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
    }

async function submitCount() {
  try {
    const payload = {
      ...productWithCount.value,
      productTypeId: productTypeId.value // 动态获取最新值
    }
    console.log(payload)
    const response = await productionWithCount(payload); // 等待 Promise 完成
    console.log(response); // 这里 response 才是 { code: 200, data: null, msg: null }

    if (response.code === 200) {
      addGoodSomeProducts(productWithCount.value.count)
      ElMessage.success("批量添加成功");
      productsWithCountForm.value = false;
    }
  } catch (error) {
    console.error("请求出错:", error);
    ElMessage.error("操作失败");
  }
}
onMounted(() => {
  fetchOperation()
  getProductByOperationId()
  loadCounts()
  loadOptions()
  fetchWorkOrders()
  getNeedMaterials()
  // getNeedMaterials()
  console.log("userStore:", userStore);
})
</script>

<style scoped>
.param-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
}

/* 当只有一个卡片时的特殊样式 */
.param-card.single-card {
  grid-column: 1 / -1;  /* 占满整行 */
  max-width: 800px;     /* 设置最大宽度 */
  margin: 0 auto;       /* 水平居中 */
}
.operation-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  animation: fadeIn 0.5s ease;
}
.param-card:only-child {
  width: 80%;
  max-width: 800px;
  margin: 0 auto;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 主卡片样式 */
.operation-card {
  margin-bottom: 30px;
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, #f9f9ff 0%, #f0f2ff 100%);
}

.card-header {
  padding: 16px 20px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
}

.operation-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  color: #409EFF;
  font-size: 24px;
}

.qa-tag {
  font-weight: bold;
  padding: 0 10px;
  height: 28px;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 工序信息样式 */
.operation-info {
  padding: 0 20px 20px;
}

.info-item {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.info-icon {
  font-size: 20px;
  color: #409EFF;
  margin-top: 3px;
}

.info-label {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.info-value {
  margin: 5px 0 0;
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

.info-row {
  display: flex;
  gap: 30px;
}

.info-col {
  flex: 1;
  display: flex;
  gap: 12px;
  min-width: 0;
}

.info-divider {
  margin: 16px 0;
}

/* 参数标题样式 */
.section-header {
  display: flex;
  align-items: center;
  margin: 40px 0 25px;
}

.section-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #dcdfe6, transparent);
}

.section-title {
  margin: 0 20px;
  font-size: 20px;
  font-weight: 500;
  color: #555;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 参数卡片样式 */
.param-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
}

.param-card {
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: 1px solid #ebeef5;
}

.param-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.param-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px;
}

.param-name {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
}

.param-content {
  padding: 0 20px 20px;
}

.value-row {
  margin-bottom: 12px;
}

.param-value {
  text-align: center;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s;
}

.param-value:hover {
  transform: scale(1.03);
}

.param-value.standard {
  background: rgba(103, 194, 58, 0.1);
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.param-value.min {
  background: rgba(230, 162, 60, 0.1);
  border: 1px solid rgba(230, 162, 60, 0.3);
}

.param-value.max {
  background: rgba(245, 108, 108, 0.1);
  border: 1px solid rgba(245, 108, 108, 0.3);
}

.label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
}

.value {
  font-size: 20px;
  font-weight: bold;
  margin: 0;
}

/* 参数描述样式 */
.param-description {
  margin-top: 16px;
}

.desc-divider {
  margin: 12px 0;
}

.desc-content {
  display: flex;
  gap: 8px;
  background: #f8f8f8;
  padding: 12px;
  border-radius: 6px;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.desc-icon {
  color: #909399;
  font-size: 16px;
  margin-top: 2px;
}

/* 空状态提示 */
.empty-tip {
  margin: 40px 0;
  padding: 40px 0;
  background: #fafafa;
  border-radius: 8px;
}
</style>